﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows;

public class Door : MonoBehaviour
{
    public bool state;
    public bool stayopen = false;
    [System.Serializable]
    public class Group
    {
        public List<SingleButton> buttons;
        public bool groupReady=false;
        [System.Serializable]
        public class SingleButton
        {
            //public bool ButtonOn = true;
            public ButtonBasic button;
            public bool state=false;
        }
    }
    public List<Group> groups;
    public void Receiver(ButtonBasic button,bool value)
    {
        foreach(var item in groups)
        {
            foreach(var thebutton in item.buttons)
            {
                if (thebutton.button == button)
                {
                    thebutton.state = value;
                    bool tmp = true;
                    foreach(var butt in item.buttons)
                    {
                        if (!butt.state)
                        {
                            tmp = false;
                            break;
                        }
                    }
                    item.groupReady = tmp;
                    tmp = false;
                    foreach(var again in groups)
                    {
                        if (again.groupReady)
                        {
                            tmp = true;
                            break;
                        }
                    }
                    State(tmp);
                    return;
                }
            }
        }
    }
    protected void State(bool value)
    {
        if (value != state)
        {
            state = value;
            if (state)
            {
                Open();
            }
            else
            {
                Close();
            }
        }
    } //尝试改变
    protected Rigidbody2D body;
    protected new SpriteRenderer renderer;
    protected Sprite on, off;
    protected virtual void Open()
    {
        state = true;
        body.simulated = false;
        renderer.sprite = on;
    }
    protected virtual void Close()
    {
        if (stayopen) return;
        state = false;
        body.simulated = true;
        renderer.sprite = off;
    }
    protected virtual void Start()
    {
        body = gameObject.GetComponent<Rigidbody2D>();
        on = Resources.Load<Sprite>("OpenDoor");
        off = Resources.Load<Sprite>("ClosedDoor");
        renderer = GetComponent<SpriteRenderer>();
    }
}
